package com.project.fiveCerealsSavoury.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.project.fiveCerealsSavoury.dao.TradeDao;
import com.project.fiveCerealsSavoury.domain.Trade;
import com.project.fiveCerealsSavoury.domain.TradeStatus;
import com.project.fiveCerealsSavoury.exception.BizException;
import com.project.fiveCerealsSavoury.service.TradeService;
import com.project.fiveCerealsSavoury.transfer.Page;
import com.project.fiveCerealsSavoury.transfer.UserPage;

@Service
@Transactional
public class TradeServiceImpl implements TradeService {
	@Autowired
	private TradeDao tradeDao;
	@Override
	public boolean tradeAdd(Trade trade) throws BizException {
		if(trade.getPreMoney()==null)throw new BizException("初始金额不为null");
		if(trade.getAftMoney()==null)throw new BizException("结算金额不为null");
		if(trade.getTime()==null)throw new BizException("交易时间不为null");
		if(trade.getName()==null)throw new BizException("用户名不为null");
		if(trade.getUserId()==null)throw new BizException("用户id不为null");
		if(trade.getTradeStatus()==null)throw new BizException("类型不为null");
		if(trade.getTradeMoney()==null)throw new BizException("交易额不为null");
		if(trade.getWeight()==null)throw new BizException("重量不为null");
		if(trade.getOrderId()==null)throw new BizException("订单的id不为null");
		tradeDao.tradeAdd(trade);
		return true;
	}

	@Override
	public Page listQuery(UserPage userPage,Integer userId) throws BizException {
		List<Trade> users = new ArrayList<>();
		Page jsonPage = new Page();
		List<Trade> list = tradeDao.teadeQuery(userId,TradeStatus.USER);
		int count = tradeDao.counts(userId,TradeStatus.USER);
		int maxTotal = count / userPage.getPageSize() + (count % userPage.getPageSize() > 0 ? 1 : 0);
		if(userPage.getPageIndex()>maxTotal){
			userPage.setPageIndex(maxTotal);
		}else if (userPage.getPageIndex()<1) {
			userPage.setPageIndex(1);
		}
		jsonPage.setPageIndex(userPage.getPageIndex());
		//当前下标
		int aginIndex =(userPage.getPageIndex()-1)*userPage.getPageSize(); 
		//结束下标
		int	 endIndex =aginIndex +userPage.getPageSize();
		if(endIndex>count){
			endIndex = count;
		}
		int i=0;
		for(Trade user : list){
			if (i>=aginIndex && i<endIndex) {
				users.add(user);
			}
			i++;
		}
			jsonPage.setTotal(maxTotal);
			jsonPage.setList(users);
			return jsonPage;
	}

	@Override
	public List<Trade> listStatus(TradeStatus tradeStatus) throws BizException {
		if (tradeStatus == null)
			throw new BizException("类型不为null");
		return tradeDao.interioRquery(tradeStatus);
	}

}
